<script lang="ts" setup>
import {useRoute, useRouter} from "vue-router";
import {onMounted, ref} from "vue";
import {useUserStore} from "../../store/UserStore.ts";
import type {OldName, UserDetail} from "../../network/types/User.ts";
import {accountStatusDes} from "../../network/types/AccountStatus.ts";
import {setWindowTitle, todo} from "../../utils/Utils.ts";
import {useItemStore} from "../../store/ItemStore.ts";
import {ItemType, type ItemTypeInfo} from "../../network/types/Item.ts";
import ForumIconName from "../../components/entrance/ForumIconName.vue";
import UserShare from "../../components/share/UserShare.vue";
import ContentRender from "../../components/content/ContentRender.vue";
import {useMessageStore} from "../../store/MessageStore.ts";
import {ElMessage, ElMessageBox} from "element-plus";
import {PriMsgRoute} from "../index.ts";
import {useAccountStore} from "../../store/AccountStore.ts";
import UserPostRoute from "../../components/routes/UserPostRoute.vue";
import PostTextArea from "../../components/post/PostTextArea.vue";
import ItemTabs from "../../components/items/ItemTabs.vue";
import {UserBuffType} from "../../network/types/UserBuff.ts";
import ForumRoute from "../../components/routes/ForumRoute.vue";


interface Description {
  label: string
  value: string | number | undefined
}

const route = useRoute()
const router = useRouter()
const userStore = useUserStore();
const itemStore = useItemStore();
const loading = ref(false)
const showPriMsgDialog = ref(false)
const showSignatureDialog = ref(false)
const showItemDialog = ref(false)
const userId = ref<number>()
const username = ref<string>()
const detail = ref<UserDetail>()
const descriptions = ref<Description[]>([])
const medals = ref<ItemTypeInfo[]>([])
const oldName = ref<OldName[]>([])

const priUsers = ref<string[]>()
const priTitle = ref<string>()
const priContent = ref<string>()
const signatureContent = ref<string>()

setWindowTitle("用户中心")

if (route.params.userId) userId.value = Number(route.params.userId)
if (route.params.username) username.value = route.params.username?.toString()

const request = async () => {
  loading.value = true
  try {
    detail.value = await userStore.detail(userId.value, username.value)
  } catch (e) {
    detail.value = await userStore.detailHtml(userId.value, username.value)
  }
  loading.value = false
  console.log(detail.value)
  if (!detail.value.userId) {
    ElMessage.error("用户不存在")
    window.history.back()
    return
  }

  userId.value = detail.value?.userId
  priUsers.value = [detail.value.username]

  descriptions.value = [
    {label: 'UID', value: detail.value?.userId},
    {label: '用户组', value: `${detail.value?.groupName} (${detail.value?.groupId})`},
    {label: '状态', value: detail.value?.status && accountStatusDes(detail.value?.status)},
    {label: '威望', value: detail.value?.prestige && (detail.value?.prestige / 10)},
    {label: '注册时间', value: detail.value?.regDatetime?.short},
    {label: '发帖数', value: detail.value?.postCount},
    {label: 'IP属地', value: detail.value?.ipLocation},
    {label: '总赞数', value: detail.value?.totalAgree},
    {label: '总礼物', value: detail.value?.totalGifts},
    {label: '被关注', value: detail.value?.followedCount},
    {label: '关注', value: detail.value?.followCount},
    // {label: '', value: ''},
  ].filter(item => item.value)

  if (detail.value?.medalId) requestMedalInfo(detail.value?.medalId)

  if (detail.value?.usernameChanged) requestOldName(detail.value?.userId)

  setWindowTitle(`${detail.value?.username} - 用户中心`)
}

const requestOldName = (userId: number) => {
  userStore.oldName(userId).then(res => oldName.value = res)
}

const requestMedalInfo = (medalId: number[]) => {
  itemStore.infoByType(2, medalId).then(res => medals.value = res)
}

const newPriMsg = (title: string | undefined, content: string | undefined, users: string[] | undefined) => {
  if (!title || !content || !users || users.length === 0) {
    ElMessage.warning("标题，正文，用户列表均不能为空")
    return
  }
  useMessageStore().new(title, content, users).then(res => {
    ElMessage.success(res)
    showPriMsgDialog.value = false
    // 跳转到私信列表
    router.push({name: PriMsgRoute.LIST})
  }).catch(r => {
    if (r.error) {
      ElMessage.error(r.error[0])
    } else {
      console.error(r)
    }
  })
}

const addBlockUser = () => {
//   弹窗确认是否拉黑
  const id = detail.value?.userId || userId.value
  const name = detail.value?.username || username.value
  if (!id || !name) return

  ElMessageBox.confirm(`即将拉黑用户 ${name}`, '提示', {type: 'warning'}).then(() => {
    userStore.addBlockUser({userId: id, username: name}).then(res => {
      ElMessage.success(res)
      // 刷新拉黑列表
      userStore.blockConfigGet(true)
    })
  })
}

const deleteBlockUser = () => {
  const id = detail.value?.userId || userId.value
  const name = detail.value?.username || username.value
  if (!id || !name) return

  ElMessageBox.confirm(`即将取消拉黑用户 ${name}`, '提示', {type: 'warning'}).then(() => {
    userStore.delBlockUser(id).then(res => {
      ElMessage.success(res)
      // 刷新拉黑列表
      userStore.blockConfigGet(true)
    })
  })
}

const sendPost = (content: string) => {
  console.log(content)
  const uid = detail.value?.userId
  if (!uid) return
  userStore.signatureSet(uid, content).then(res => {
    ElMessage.success(res)
  })
}

onMounted(() => {
  request()
  userStore.blockConfigGet()
})

</script>

<template>
  <div v-loading="loading">
    <div v-if="detail && detail.userId" class="text-align-start">
      <h2 style="margin-top: 3px">
        {{ detail.username }}
        <user-share :size="30" :user-id="detail.userId" :username="detail.username"/>
      </h2>
      <h3>基本信息</h3>
      <el-descriptions border>
        <template #default>
          <el-descriptions-item v-for="item in descriptions" :label="item.label" class-name="item-bg-color0" label-class-name="item-bg-color1">
            {{ item.value }}
          </el-descriptions-item>
          <el-descriptions-item class-name="item-bg-color0" label="发言" label-class-name="item-bg-color1">
            <user-post-route :user-id="detail.userId">[ 主题 ]</user-post-route>
            <user-post-route :user-id="detail.userId" reply>[ 回复 ]</user-post-route>
          </el-descriptions-item>
        </template>
        <template #extra>
          <!--操作按钮-->
          <el-button-group v-if="userId!==useAccountStore().getAccountUserId()">
            <el-button type="primary" @click="showItemDialog=true">道具</el-button>
            <el-button v-if="detail.followed" type="danger" @click="todo()">取关</el-button>
            <el-button v-else type="primary" @click="todo()">关注</el-button>
            <el-button type="primary" @click="showPriMsgDialog=true">私信</el-button>
            <el-button v-if="userStore.blockConfig?.hasUser(userId)" type="warning" @click="deleteBlockUser">取消拉黑</el-button>
            <el-button v-else type="danger" @click="addBlockUser">拉黑</el-button>
          </el-button-group>
        </template>
      </el-descriptions>
      <div v-if="detail&&detail.usernameChanged">
        <h3>曾用名</h3>
        <ul>
          <li v-for="on in oldName">
            <b>{{ on.username }}</b>
            <span> 在 {{ on.before?.short }} 之前</span>
          </li>
        </ul>
      </div>
      <div v-if="detail.avatars">
        <h3>头像</h3>
        <el-image v-for="avatar in detail.avatars" v-if="detail.avatars" :src="avatar" style="margin-right: 5px"/>
      </div>

      <div v-if="detail.buffs && detail.buffs.length>0"><h3>BUFF</h3>
        <ul>
          <li v-for="buff in detail.buffs">
            <span v-if="buff.type===UserBuffType.MUTED">
              <span v-if="buff.forumName&&buff.extraData">在版面
                <forum-route :fid="buff.extraData">{{ buff.forumName }}</forum-route>
                禁言</span>
              <span v-else>全版面禁言</span>
            </span>
            <span v-else>{{ buff.description }}</span>
            <span style="margin-left: 10px">{{ buff.start.short }}</span>
            <span> - </span>
            <span>{{ buff.end.short }}</span>
          </li>
        </ul>
      </div>
      <div v-if="detail.reputations">
        <h3>声望</h3>
        <ul>
          <li v-for="reputation in detail.reputations">
            <b>{{ reputation.name }}</b>
            <span style="margin-left: 10px">{{ reputation.value }}</span>
            <el-text style="margin-left: 20px" type="info">{{ reputation.description }}</el-text>
          </li>
        </ul>
      </div>
      <div v-if="medals && medals.length>0">
        <h3>徽章</h3>
        <div>
          <ul style="margin: 5px 0">
            <li v-for="medal in medals" style="margin-top: 5px">
              <el-row>
                <el-image :src="medal.url.replace('https://img4.nga.178.com/','/static/res/')"
                          style="width: 24px"/>
                <b style="margin-left: 5px">{{ medal.name }}</b>
                <el-text style="margin-left: 20px" type="info">{{ medal.description }}</el-text>
              </el-row>
            </li>
          </ul>
        </div>
      </div>
      <div v-if="detail.adminForums">

        <h3>管理版面</h3>
        <div>
          <forum-icon-name v-for="f in detail.adminForums" :fid="f.id" :name="f.name"/>
        </div>
      </div>
      <div v-if="detail.signature">
        <h3>签名 -
          <el-button type="primary" @click="showSignatureDialog=true;signatureContent = signatureContent || detail.signature">修改</el-button>
        </h3>
        <div style="    border: 1px dashed #afc6cf;">
          <content-render :data="detail.signatureNodes || []"/>
        </div>
      </div>

    </div>

    <el-dialog v-model="showPriMsgDialog" title="发起私信">
      <el-select v-model="priUsers" allow-create filterable multiple placeholder="请选择邀请的用户，可填写用户名"/>
      <el-input v-model="priTitle" placeholder="标题(必填)"/>
      <el-input v-model="priContent" placeholder="正文(必填)" type="textarea"/>
      <el-button type="success" @click="newPriMsg(priTitle,priContent,priUsers)">发送</el-button>
    </el-dialog>

    <!--  修改签名弹窗-->
    <el-dialog v-model="showSignatureDialog" title="修改签名" width="70%">
      <post-text-area v-model="signatureContent" @send-post="sendPost"/>
    </el-dialog>

    <!-- 道具弹窗-->
    <el-dialog v-model="showItemDialog" title="使用道具" width="70%">
      <item-tabs :item-type="ItemType.TO_USER" :user-id="detail?.userId"/>
    </el-dialog>
  </div>

</template>

<style scoped>


h3 {
  margin: 10px 0
}

ul {
  margin: 5px 0
}
</style>